/*-
 * $Id: Main.java 4 2010-11-04 07:39:56Z andrewbass $
 */
package com.google.code.getwrong.ssh2.jsch;

import java.io.File;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

/**
 * @author Andrew ``Bass'' Shcheglov (andrewbass@gmail.com)
 * @author $Author: andrewbass $
 * @version $Revision: 4 $, $Date:: $
 */
abstract class Main {
	private Main() {
		assert false;
	}

	/**
	 * @param args
	 * @throws JSchException
	 */
	public static void main(final String args[]) throws JSchException {
	        final String prvkey = System.getProperty("user.home") + File.separatorChar + ".ssh" + File.separatorChar + "id_rsa";
	        System.out.println(prvkey);

		final JSch jsch = new JSch();
		jsch.addIdentity(prvkey);

		final String userAtHost;
		String lportRhostRport;
		if (args.length == 2) {
			userAtHost = args[0];
			lportRhostRport = args[1];
		} else {
			System.err.println("Usage: " + Main.class.getName() + " <username>@<hostname> <lport>:<rhost>:<rport>");
			return;
		}
		final String user = userAtHost.substring(0, userAtHost.indexOf('@'));
		final String host = userAtHost.substring(userAtHost.indexOf('@') + 1);

		final Session session = jsch.getSession(user, host, 22);

		final int lport = Integer.parseInt(lportRhostRport.substring(0, lportRhostRport.indexOf(':')));
		lportRhostRport = lportRhostRport.substring(lportRhostRport.indexOf(':') + 1);
		final String rhost = lportRhostRport.substring(0, lportRhostRport.indexOf(':'));
		final int rport = Integer.parseInt(lportRhostRport.substring(lportRhostRport.indexOf(':') + 1));

		session.setUserInfo(new UserInfo() {
			/**
			 * @see UserInfo#getPassword()
			 */
			@Override
			public String getPassword() {
				return null;
			}

			/**
			 * @see UserInfo#promptYesNo(String)
			 */
			@Override
			public boolean promptYesNo(final String str) {
				return true;
			}

			/**
			 * @see UserInfo#getPassphrase()
			 */
			@Override
			public String getPassphrase() {
				return null;
			}

			/**
			 * @see UserInfo#promptPassphrase(String)
			 */
			@Override
			public boolean promptPassphrase(final String message) {
				return true;
			}

			/**
			 * @see UserInfo#promptPassword(String)
			 */
			@Override
			public boolean promptPassword(final String message) {
				return true;
			}

			/**
			 * @see UserInfo#showMessage(String)
			 */
			@Override
			public void showMessage(final String message) {
				System.out.println(message);
			}
		});

		session.connect();

		final int assingedPort = session.setPortForwardingL("127.0.0.1", lport, rhost, rport);
		System.out.println("localhost:" + assingedPort + " -> " + rhost + ":" + rport);
	}
}
